﻿using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using EnvDTE;

namespace tomenglertde.SetupProject.ViewModel
{
    internal static class DteExtensions
    {
        /// <summary>
        /// Gets all projects in the solution.
        /// </summary>
        /// <param name="solution">The solution.</param>
        /// <returns>The projects.</returns>
        public static IEnumerable<Project> GetProjecs(this Solution solution)
        {
            Contract.Requires(solution != null);
            Contract.Requires(solution.Projects != null);
            Contract.Ensures(Contract.Result<IEnumerable<Project>>() != null);

            var items = new List<Project>();

            foreach (var project in solution.Projects.Cast<Project>())
            {
                items.Add(project);

                GetSubProjects(project.ProjectItems, items);
            }

            return items;
        }

        private static void GetSubProjects(this IEnumerable projectItems, ICollection<Project> items)
        {
            if (projectItems == null)
                return;

            foreach (var projectItem in projectItems.Cast<ProjectItem>())
            {
                projectItem.GetSubProjects(items);
            }
        }

        private static void GetSubProjects(this ProjectItem projectItem, ICollection<Project> items)
        {
            var subProject = projectItem.SubProject;

            if (subProject == null) 
                return;

            items.Add(subProject);

            subProject.ProjectItems.GetSubProjects(items);
        }
    }
}
